package com.canyou.utils;

import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取地址类
 *
 * @author cgz
 */
@Slf4j
public final class AddressUtils {

    private AddressUtils() {
    }

    /**
     * ip地址库接口链接
     */
    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static String getRealAddressByIp(String ip) {
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网";
        }
        try {
            String rspStr = HttpUtil.post(IP_URL, "ip=" + ip, 3000);
            if (StringUtils.isBlank(rspStr)) {
                log.warn("获取地理位置失败 {}", ip);
                return "";
            }
            JsonNode jsonNode = OBJECT_MAPPER.readTree(rspStr);
            JsonNode data = jsonNode.path("data");
            String region = data.path("region").asText();
            String city = data.path("city").asText();
            return region + city;
        } catch (Exception e) {
            log.warn("获取地理位置异常 {}", ip, e);
        }
        return "";
    }
}
